import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.settings import api_settings

from goods.models import SKU
from users import constants
from users.models import User, Address
from celery_tasks.email.tasks import send_verify_email


class CreateUserSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField(
        min_length=5,
        max_length=20,
        error_messages={
            'min_length': '用户名为5-20个字符',
            'max_length': '用户名为5-20个字符'
        }
    )
    password = serializers.CharField(
        write_only=True,
        min_length=8,
        max_length=20,
        error_messages={
            'min_length': '密码为8-20个字符',
            'max_length': '密码为8-20个字符'
        }
    )
    password2 = serializers.CharField(write_only=True)
    mobile = serializers.CharField()
    sms_code = serializers.CharField(write_only=True)
    allow = serializers.BooleanField(write_only=True)
    # 增加token字段,实现状态保持,次子字段只需输出操作,
    token = serializers.CharField(label='登录状态token', read_only=True)

    def validate_username(self, value):
        if User.objects.filter(username=value).count()>0:
            raise serializers.ValidationError("用户名存在")
        return value

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def validate_allow(self, value):
        if not value:
            raise serializers.ValidationError("必须同意协议")
        return value

    def validate(self, attrs):
        # ------------------校验短信验证码-------------------
        # 连接redis,生成redis客户端
        redis_cli = get_redis_connection("sms_code")
        sms_code_redis = redis_cli.get('sms_code_'+attrs.get('mobile'))
        if not sms_code_redis:
            raise serializers.ValidationError("验证码已过期")
        # 删除redis中的验证码
        redis_cli.delete('sms_code_'+attrs.get('mobile'))
        sms_code_redis = sms_code_redis.decode()
        sms_code_request = attrs.get('sms_code')
        if sms_code_redis != sms_code_request:
            raise serializers.ValidationError("验证码错误")
        # ------------------校验密码-------------------
        pwd1 = attrs.get('password')
        pwd2 = attrs.get('password2')
        if pwd1 != pwd2:
            raise serializers.ValidationError("两次输入的密码不一致")

        return attrs

    def create(self, validated_data):
        """注册/创建用户"""
        user = User()
        user.username = validated_data.get('username')
        user.mobile = validated_data.get('mobile')
        # 这里密码需要加密处理
        user.set_password(validated_data.get('password'))
        # 保存
        user.save()
        # 服务器生成登录状态token,这里不需要将token保存在数据库,因此写在外面
        jwt_payload_hanlder = api_settings.JWT_PAYLOAD_HANDLER  # 取得payload处理器
        jwt_encode_hanlder = api_settings.JWT_ENCODE_HANDLER  # 取得token加密处理器
        # 注: 若想对payload中的内容进行修改,那么需要考虑api_settings.JWT_PAYLOAD_HANDLER,具体应是修改/重写jwt_payload_handler方法(utils.py文件中),看源码
        payload = jwt_payload_hanlder(user)
        token = jwt_encode_hanlder(payload)
        user.token = token
        print(token)

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        # 修改对象instance
        instance.email = validated_data['email']
        instance.save()
        # 生成验证邮箱的url(激活地址),谁调用就是谁在进行邮箱验证
        verify_url = instance.generate_verify_email_url()
        print(verify_url)
        # 由于具体邮箱验证耗时,故可异步处理,收件人email,激活地址verify_url
        send_verify_email.delay(email, verify_url)

        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """用户收货地址序列化器"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市id', required=True)
    district_id = serializers.IntegerField(label='区id', required=True)

    class Meta:
        model = Address
        # 在此时,user并不需要传递,表单也没填,后续获取user是通过request.user获取当前登陆的用户
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """新增"""
        # 在提供序列化器对象时,drf会想对象的context属性补充三个数据request/format/view,这三个数据对象可以在定义序列化器时使用
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """收货地址标题序列化器"""
    class Meta:
        model = Address
        fields = ['title']


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """添加用户浏览历史序列化器"""
    sku_id = serializers.IntegerField(label='商品sku编号', min_value=1)

    def validate_sku_id(self, value):
        """检验sku_id是否存在"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """保存"""
        # 在提供序列化器时,drf会向对象的context属性补充三个数据:request/format/view
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        # 连接redis
        redis_conn = get_redis_connection('history')

        """
        # 根据不同的用户构造键
        key = 'history_%d' % self.context['request'].user.id
        # 1.删除sku_id
        redis_conn.lrem(key, 0, sku_id)
        # 2.添加
        redis_conn.lpush(key, sku_id)
        # 3.判断长度,只保存最多5条记录
        if redis_conn.llen(key) > constants.USER_BROWSING_HISTORY_COUNTS_LIMIT:
            # 4.如果超过长度则删除最后一个
            redis_conn.rpop(key)
        """

        # pipeline 管道,用来批量提交命令,还可以用来实现事务(这里不考虑,可参考http://www.cnblogs.com/kangoroo/p/7535405.html)
        pl = redis_conn.pipeline()

        # 移除已经存在的本商品浏览记录
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 添加新的浏览记录
        pl.lpush('history_%s' % user_id, sku_id)
        # 只保存最多5条记录,ltrim其实就是切片
        pl.ltrim('history_%s' % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)

        pl.execute()
        # return {'sku_id': sku_id}
        return validated_data
